import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {GnLoginUser, GnMessageService} from 'geminis-ng';
import {ActivatedRoute, Router} from '@angular/router';
import {OAuthSession} from './OAuthSession';
import {OAuthConfig} from './OAuthConfig';

@Component({
  selector: 'portal-logining',
  template: ``
})
export class LoginingComponent implements OnInit {

  constructor(private http: HttpClient,
              private loginUser: GnLoginUser,
              private activateRoute: ActivatedRoute,
              private oauthSession: OAuthSession,
              private oauthConfig: OAuthConfig,
              private messageService: GnMessageService,
              private router: Router) {
  }

  ngOnInit(): void {
    this.activateRoute.queryParams.subscribe(value => {

      if (value.state !== this.oauthSession.state) {
        throw new Error('state不匹配');
      }

      this.oauthConfig.load()
        .subscribe(config => {
          const params = [
            'grant_type=authorization_code',
            'redirect_uri=' + encodeURIComponent(this.oauthConfig.redirectUri),
            'client_id=' + this.oauthConfig.clientId,
            'code=' + value.code
          ];

          if (this.oauthConfig.usePkce) {
            params.push(
              'code_verifier=' + this.oauthSession.codeVerifier
            );
          } else {
            params.push(
              'client_secret=' + this.oauthConfig.clientSecret
            );
          }

          this.http.post(config.oidcConfig.token_endpoint, params.join('&'), {
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          })
            .subscribe((resp: any) => {
              this.http.post('/api/resources/oauth/token', resp.id_token)
                .subscribe((newToken: any) => {
                  sessionStorage.setItem('OAuthIdToken', resp.id_token);
                  sessionStorage.setItem('Authorization', newToken.token);

                  this.loginUser.isLogin = true;
                  this.loginUser.username = newToken.username;
                  this.loginUser.name = newToken.name;
                  this.loginUser.authorities = newToken.authorities;
                  sessionStorage.setItem('LoginUser', JSON.stringify(this.loginUser));

                  this.router.navigateByUrl('/');
                });
            }, error => {
              this.messageService.error('获取token错误，' + error.message);
            });

        });
    });
  }
}
